package com.zoran.study.spring.controller.interceptors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * RequestLoggingInterceptor
 *
 * @author zouxm
 * @date 2018/6/22
 */
public class RequestLoggingInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingInterceptor.class);

    public RequestLoggingInterceptor() {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.info("[{}] Response status code {}, duration {} ms", new Object[]{this.requestId(request), Integer.valueOf(response.getStatus()), this.duration(request)});
    }

    private String requestId(HttpServletRequest request) {
        return (String) request.getAttribute("com.fincloud.request.uuid");
    }

    private String duration(HttpServletRequest request) {
        Object requestArriveTime = request.getAttribute("com.fincloud.request.arrival-time");
        if (requestArriveTime == null) {
            return "N/A";
        } else {
            String attr = String.valueOf(requestArriveTime);
            return String.valueOf(System.currentTimeMillis() - Long.valueOf(attr).longValue());
        }
    }
}

